19. 练习:标准库
Start Quiz:
# print e to the power of 3 using the math module
练习:密码生成器
写一个叫做
generate_password
的函数,该函数会从提供的单词文件中随机选择三个单词,并将它们连接成一个字符串。我们已经在起始代码中提供了从文件中读取数据的代码,你需要利用这些部分构建一个密码。
Start Quiz:
# Use an import statement at the top
word_file = "words.txt"
word_list = []
#fill up the word_list
with open(word_file,'r') as words:
for line in words:
# remove white space and make everything lowercase
word = line.strip().lower()
# don't include words that are too long or too short
if 3 < len(word) < 8:
word_list.append(word)
# Add your function generate_password here
# It should return a string consisting of three random words
# concatenated together without spaces
# test your function
print(generate_password())
Alice
was
beginning
to
get
very
tired
of
sitting
by
her
sister
bank
having
nothing
Once
twice
she
had
peeped
into
the
book
her
sister
was
reading
but
it
had
no
pictures
or
conversations
in
it
and
what
is
the
use
of
a
book
thought
Alice
without
pictures
or
conversations
探索标准库
在下面的练习中,请输入解决每个问题的模块名称。注意,大小写很重要!标准库中的每个模块都是全小写形式。 你可以在此处浏览库文档 。
哪个模块 ?(1)
QUESTION:
哪个模块可以告诉你当前时间和日期?
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
哪个模块?(2)
QUESTION:
哪个模块具有更改当前工作目录的方法?
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
哪个模块?(3)
QUESTION:
哪个模块可以将逗号分隔 (.csv) 文件中的每行数据读取到 Python 中?
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
哪个模块?(4)
QUESTION:
哪个模块可以帮助我们从 zip 文件中提取所有文件?
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
哪个模块?(5)
QUESTION:
哪个模块可以显示代码的运行时间?
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
我们的推荐模块
Python 标准库包含大量模块!为了帮助你熟悉那些实用的模块,我们在下面筛选了一些我们推荐的 Python 标准库模块并解释为何我们喜欢使用它们!
-
csv
:对于读取 csv 文件来说非常便利 -
collections
:常见数据类型的实用扩展,包括OrderedDict
、defaultdict
和namedtuple
-
random
:生成假随机数字,随机打乱序列并选择随机项 -
string
:关于字符串的更多函数。此模块还包括实用的字母集合,例如string.digits
(包含所有字符都是有效数字的字符串)。 -
re
:通过正则表达式在字符串中进行模式匹配 -
math
:一些标准数学函数 -
os
:与操作系统交互 -
os.path
:os
的子模块,用于操纵路径名称 -
sys
:直接使用 Python 解释器 -
json
:适用于读写 json 文件(面向网络开发)
希望你能用上这些模块!